package manager.modulo.estoque.fonte;

import java.awt.event.KeyEvent;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.LinkedList;
import javax.swing.JOptionPane;
import javax.swing.UIManager;
import javax.swing.table.TableRowSorter;
import manager.auxiliares.AutoComplete;
import manager.auxiliares.Configurations;
import manager.auxiliares.FixedLengthDocument;
import manager.auxiliares.Format;
import manager.auxiliares.Icons;
import manager.auxiliares.MensagemExcessao;
import manager.auxiliares.WindowsFunctions;
import manager.helpers.table.TableModel;
import manager.helpers.table.TableRender;
import manager.helpers.table.TableRowComparator;
import manager.helpers.validation.TextFieldValidator;
import manager.helpers.validation.ValidationFunctions;
import manager.principal.fonte.JanelaLogin;
import manager.interfaces.InterfaceTable;
import manager.modulo.estoque.dao.ComposicaoDao;
import manager.modulo.estoque.dao.ItemComposicaoDao;
import manager.modulo.estoque.dao.InsumoDao;
import manager.modulo.estoque.enumerator.EnumUnidadeInsumo;
import manager.modulo.orcamento.dao.ItemOrcamentoDao;
import manager.modulo.orcamento.enumerator.EnumTipoItemOrcamento;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.view.JasperViewer;

/**
 *
 * @author Thiago
 */
public class JanelaComposicao extends javax.swing.JFrame {

    //Entrada de Estoque
    int idComposicao = 0;
    AutoComplete autoCompletarCentroCusto;
    int index = 0;
    TableModel tableModel;
    TableRender tableRender;
    TableRowSorter tableRowSorter;
    LinkedList<ItemComposicaoDao> listaItemComposicao;
    AutoComplete autoCompletarIdentificadorItem;
    AutoComplete autoCompletarNomeItem;

    public JanelaComposicao() {
    }

    /**
     * Creates new form UserWindow
     */
    public JanelaComposicao(int id) {
        try {
            // Define layout de acordo com o SO que estiver rodando
            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
            this.setIconImage(JanelaLogin.icon);
            initComponents();
            idComposicao = id;
            configurarJanela();
            this.setLocationRelativeTo(null);
            this.setVisible(true);
        } catch (Exception e) {
            MensagemExcessao.mostrarMensagem(e, this.getTitle());
        }
    }

    private LinkedList<String> getNomeColunasTabelaInsumos() {
        LinkedList<String> listaNomesColunas = new LinkedList<String>();
        listaNomesColunas.add("");
        listaNomesColunas.add("Item");
        listaNomesColunas.add("Tipo");
        listaNomesColunas.add("Ident.");
        listaNomesColunas.add("Nome");
        listaNomesColunas.add("Unid.");
        listaNomesColunas.add("Quant.");
        listaNomesColunas.add("Valor");
        listaNomesColunas.add("Total");
        return listaNomesColunas;
    }

    private void carregarInformacoesItemComposicao() {
        jButton2.setToolTipText("Editar");
        jButton2.setIcon(new Icons().getEdit());

        jButton2.setEnabled(true);
        jButton4.setEnabled(true);
        jButton3.setEnabled(true);
        ItemComposicaoDao itemComposicaoDao = listaItemComposicao.get(index);
        jRadioButton1.setSelected(true);

        if (itemComposicaoDao.getTipoItem() == EnumTipoItemOrcamento.TipoItemOrcamento.INSUMO) {
            jRadioButton3.setSelected(true);
            InsumoDao insumoDao = new InsumoDao();
            insumoDao.buscar(itemComposicaoDao.getIdInsumo());
            jTextField8.setText(insumoDao.getIdentificador());
            jTextField5.setText(insumoDao.getNome());
            jTextField13.setText(Double.toString(((double) itemComposicaoDao.getQuantidade()) / 100));
        } else {
            jRadioButton4.setSelected(true);
            ComposicaoDao composicaoDao = new ComposicaoDao();
            composicaoDao.buscar(itemComposicaoDao.getIdComposicao());
            jTextField8.setText(composicaoDao.getIdentificador());
            jTextField5.setText(composicaoDao.getNome());
            jTextField13.setText(Double.toString(((double) itemComposicaoDao.getQuantidade()) / 100));
        }
        jTextField8.requestFocus();
    }

    private void configureTable() {
        tableRender = new TableRender();
        tableModel = new TableModel(getNomeColunasTabelaInsumos(), tableRender, new InterfaceTable() {
            public void tableAction(int id, int columnIndex, int rowIndex) {
                if (columnIndex < 0) {
                    index = rowIndex;
                    carregarInformacoesItemComposicao();
                }
            }

            public boolean isEditableColumn(int columnIndex) {
                if (columnIndex == 0) {
                    return true;
                }
                return false;
            }
        });
        jTable1.setModel(tableModel);
        jTable1.getColumnModel().getColumn(0).setMaxWidth(30);
        jTable1.getColumnModel().getColumn(0).setMinWidth(30);
        jTable1.getColumnModel().getColumn(0).setResizable(false);
        jTable1.getColumnModel().getColumn(1).setMaxWidth(40);
        jTable1.getColumnModel().getColumn(1).setMinWidth(40);
        jTable1.getColumnModel().getColumn(1).setResizable(false);
        jTable1.getColumnModel().getColumn(2).setMaxWidth(40);
        jTable1.getColumnModel().getColumn(2).setMinWidth(40);
        jTable1.getColumnModel().getColumn(2).setResizable(false);

        jTable1.getColumnModel().getColumn(3).setMaxWidth(50);
        jTable1.getColumnModel().getColumn(3).setMinWidth(50);
        jTable1.getColumnModel().getColumn(3).setResizable(false);

        jTable1.getColumnModel().getColumn(5).setMaxWidth(40);
        jTable1.getColumnModel().getColumn(5).setMinWidth(40);
        jTable1.getColumnModel().getColumn(5).setResizable(false);
        jTable1.getColumnModel().getColumn(6).setMaxWidth(50);
        jTable1.getColumnModel().getColumn(6).setMinWidth(50);
        jTable1.getColumnModel().getColumn(6).setResizable(false);
        jTable1.getColumnModel().getColumn(7).setMaxWidth(60);
        jTable1.getColumnModel().getColumn(7).setMinWidth(60);
        jTable1.getColumnModel().getColumn(7).setResizable(false);
        jTable1.getColumnModel().getColumn(8).setMaxWidth(70);
        jTable1.getColumnModel().getColumn(8).setMinWidth(70);
        jTable1.getColumnModel().getColumn(8).setResizable(false);
        TableRowComparator tableRowComparator = new TableRowComparator();
        tableRowSorter = tableRowComparator;
        jTable1.setRowSelectionAllowed(false);

        buscarTabela();
    }

    private void configurarCamposComposicao() {
        ((TextFieldValidator) jTextField4).validarCampo();
        ((TextFieldValidator) jTextField6).validarCampo();

        configurarCamposInsumos();
    }

    private void configurarCamposInsumos() {
        ((TextFieldValidator) jTextField13).validarCampo();
        if (jRadioButton2.isSelected()) {
            ((TextFieldValidator) jTextField8).validarCampo();
            jLabel8.setForeground(Configurations.getFieldValidationOk());
        } else {
            ((TextFieldValidator) jTextField5).validarCampo();
            jLabel13.setForeground(Configurations.getFieldValidationOk());
        }
    }

    private void limparCamposItens(boolean cancelarEdicao) {
        jTextField8.setText("");
        jTextField5.setText("");
        jTextField9.setText("");
        jTextField13.setText("");
        autoCompletarIdentificadorItem.setSearchWord("");
        autoCompletarNomeItem.setSearchWord("");

        jScrollPane3.setVisible(false);

        configurarCamposInsumos();
        if (cancelarEdicao) {
            jButton2.setToolTipText("Adicionar");
            jButton2.setIcon(new Icons().getAdd());

            jButton3.setEnabled(false);
            jButton4.setEnabled(false);
        }
    }

    private void buscarTabela() {
        LinkedList searchResult = new LinkedList();

        LinkedList<Integer> columnId = new LinkedList<Integer>();
        LinkedList<String> colunaNumeroItem = new LinkedList<String>();
        LinkedList<String> colunaTipoItem = new LinkedList<String>();
        LinkedList<String> colunaIdentificador = new LinkedList<String>();
        LinkedList<String> colunaNome = new LinkedList<String>();
        LinkedList<String> colunaUnidade = new LinkedList<String>();
        LinkedList<String> colunaQuantidade = new LinkedList<String>();
        LinkedList<String> colunaValor = new LinkedList<String>();
        LinkedList<String> colunaTotal = new LinkedList<String>();

        for (int i = 0; i < listaItemComposicao.size(); i++) {
            ItemComposicaoDao itemComposicaoDao = listaItemComposicao.get(i);
            columnId.add(i);
            colunaNumeroItem.add(Integer.toString(i + 1));
            colunaTipoItem.add(EnumTipoItemOrcamento.ConvertEnumString(itemComposicaoDao.getTipoItem()));
            if (itemComposicaoDao.getTipoItem() == EnumTipoItemOrcamento.TipoItemOrcamento.INSUMO) {
                InsumoDao insumoDao = new InsumoDao();
                insumoDao.buscar(itemComposicaoDao.getIdInsumo());
                colunaIdentificador.add(insumoDao.getIdentificador());
                colunaNome.add(insumoDao.getNome());
                colunaUnidade.add(EnumUnidadeInsumo.ConvertEnumString(insumoDao.getUnidadeInsumo()));
                colunaValor.add(Format.formatarMonetario(Double.toString(((double) itemComposicaoDao.getValorUnitario()) / 100)));
                colunaTotal.add(Format.formatarMonetario(Double.toString(((double) insumoDao.getValorUnitario() * itemComposicaoDao.getQuantidade()) / 10000)));
            } else {
                ComposicaoDao composicaoDao = new ComposicaoDao();
                composicaoDao.buscar(itemComposicaoDao.getIdComposicao());
                colunaIdentificador.add(composicaoDao.getIdentificador());
                colunaNome.add(composicaoDao.getNome());
                colunaUnidade.add(EnumUnidadeInsumo.ConvertEnumString(composicaoDao.getUnidadeInsumo()));
                colunaValor.add(Format.formatarMonetario(Double.toString(((double) itemComposicaoDao.getValorUnitario()) / 100)));
                colunaTotal.add(Format.formatarMonetario(Double.toString(((double) itemComposicaoDao.getValorUnitario() * itemComposicaoDao.getQuantidade()) / 10000)));

            }
            colunaQuantidade.add(Double.toString(((double) itemComposicaoDao.getQuantidade()) / 100));
        }

        if (listaItemComposicao.size() > 0) {
            searchResult.add(columnId);
            searchResult.add(Format.getBooleanLinkedList(columnId.size()));
            searchResult.add(colunaNumeroItem);
            searchResult.add(colunaTipoItem);
            searchResult.add(colunaIdentificador);
            searchResult.add(colunaNome);
            searchResult.add(colunaUnidade);
            searchResult.add(colunaQuantidade);
            searchResult.add(colunaValor);
            searchResult.add(colunaTotal);
        }

        tableModel.update(searchResult);
        jTable1.setDefaultRenderer(Object.class, tableRender);
        tableRowSorter.setModel(tableModel);

        jTable1.setRowSorter(tableRowSorter);
    }

    private LinkedList<String> validarCamposEntradaEstoque() {
        LinkedList<String> fieldList = new LinkedList<String>();
        if (!((TextFieldValidator) jTextField4).validarCampo()) {// Documento
            fieldList.add(((TextFieldValidator) jTextField4).getjLabel().getText());
        }
        if (!((TextFieldValidator) jTextField6).validarCampo()) {// Documento
            fieldList.add(((TextFieldValidator) jTextField6).getjLabel().getText());
        }
        if (listaItemComposicao.size() == 0) {
            fieldList.add("Lista de insumos vazia.");
        }
        return fieldList;
    }

    private LinkedList<String> validarCamposInsumos() {
        LinkedList<String> fieldList = new LinkedList<String>();
        if (jRadioButton2.isSelected()) {
            if (!((TextFieldValidator) jTextField8).validarCampo()) {// Identificador
                fieldList.add(((TextFieldValidator) jTextField8).getjLabel().getText());
            }
        } else {
            if (!((TextFieldValidator) jTextField5).validarCampo()) {// Nome
                fieldList.add(((TextFieldValidator) jTextField5).getjLabel().getText());
            }
        }
        if (!((TextFieldValidator) jTextField13).validarCampo()) {// Quantidade
            fieldList.add(((TextFieldValidator) jTextField13).getjLabel().getText());
        }
        return fieldList;
    }

    private void adicionarComposicao() {
        try {
            try {
                if (listaItemComposicao.size() > 0) {
                    if (ComposicaoDao.getIdComposicaoPorIdentificador(jTextField4.getText()) == 0 && ComposicaoDao.getIdComposicaoPorNome(jTextField4.getText()) == 0) {
                        JanelaLogin.connection.setAutoCommit(false);

                        ComposicaoDao composicaoDao = new ComposicaoDao();
                        composicaoDao.setNome(jTextField6.getText());
                        composicaoDao.setIdentificador(jTextField4.getText());
                        composicaoDao.setObservacao(jTextArea2.getText());
                        composicaoDao.setUnidadeInsumo(EnumUnidadeInsumo.ConvertStringEnum(jComboBox6.getSelectedItem().toString()));
                        composicaoDao.setValorUnitario(this.calcularValorUnitario());
                        composicaoDao.inserir();

                        for (int i = 0; i < listaItemComposicao.size(); i++) {
                            ItemComposicaoDao itemComposicaoDao = listaItemComposicao.get(i);
                            itemComposicaoDao.setIdComposicaoPai(composicaoDao.getId());
                            itemComposicaoDao.inserir();
                        }

                        JanelaLogin.connection.commit();
                        JOptionPane.showMessageDialog(null, "Composição cadastrada com sucesso.", this.getTitle(), JOptionPane.INFORMATION_MESSAGE);

                        this.dispose();
                    } else {
                        JOptionPane.showMessageDialog(null, "Esta composicao já esta cadastrada.", this.getTitle(), JOptionPane.ERROR_MESSAGE);
                    }
                } else {
                    JOptionPane.showMessageDialog(null, "Adicione pelo menos um insumo a composição.", this.getTitle(), JOptionPane.ERROR_MESSAGE);
                }
            } catch (Exception e) {
                JanelaLogin.connection.rollback();
                MensagemExcessao.mostrarMensagem(e, this.getTitle());
            } finally {
                JanelaLogin.connection.setAutoCommit(true);
            }
        } catch (Exception ex) {
            MensagemExcessao.mostrarMensagem(ex, this.getTitle());
        }
    }

    private void editarComposicao() {
        try {
            int idIdentificadorComposicao = ComposicaoDao.getIdComposicaoPorIdentificador(jTextField4.getText());
            int idNomeComposicao = ComposicaoDao.getIdComposicaoPorNome(jTextField6.getText());
            if ((idIdentificadorComposicao == 0 && idNomeComposicao == 0)
                    || (idIdentificadorComposicao == idComposicao && idNomeComposicao == 0)
                    || (idIdentificadorComposicao == 0 && idNomeComposicao == idComposicao)
                    || (idIdentificadorComposicao == idComposicao && idNomeComposicao == idComposicao)) {

                try {
                    JanelaLogin.connection.setAutoCommit(false);

                    ComposicaoDao composicaoDao = new ComposicaoDao();
                    composicaoDao.buscar(idComposicao);
                    composicaoDao.setNome(jTextField6.getText());
                    composicaoDao.setIdentificador(jTextField4.getText());
                    composicaoDao.setObservacao(jTextArea2.getText());
                    composicaoDao.setUnidadeInsumo(EnumUnidadeInsumo.ConvertStringEnum(jComboBox6.getSelectedItem().toString()));
                    composicaoDao.setValorUnitario(this.calcularValorUnitario());

                    composicaoDao.atualizar();

                    ItemComposicaoDao itemComposicaoDao = new ItemComposicaoDao();
                    itemComposicaoDao.setIdComposicaoPai(idComposicao);
                    itemComposicaoDao.deletar();

                    for (int i = 0; i < listaItemComposicao.size(); i++) {
                        ItemComposicaoDao insumoComposicaoDao = listaItemComposicao.get(i);
                        insumoComposicaoDao.setIdComposicaoPai(idComposicao);

                        insumoComposicaoDao.inserir();
                    }

                    JanelaLogin.connection.commit();

                    JOptionPane.showMessageDialog(null, "Composição atualizada com sucesso.", this.getTitle(), JOptionPane.INFORMATION_MESSAGE);
                    this.dispose();
                } catch (Exception e) {
                    JanelaLogin.connection.rollback();
                    MensagemExcessao.mostrarMensagem(e, "Atualização de Composições");
                } finally {
                    JanelaLogin.connection.setAutoCommit(true);
                }
            } else {
                JOptionPane.showMessageDialog(null, "Esta composição já esta cadastrada.", this.getTitle(), JOptionPane.ERROR_MESSAGE);
            }
        } catch (Exception ex) {
            MensagemExcessao.mostrarMensagem(ex, this.getTitle());
        }
    }

    private void adicionarItemComposicao() {
        try {
            int idInsumoBuscado = InsumoDao.getIdInsumoPorIdentificador(jTextField8.getText());
            int idComposicaoBuscada = ComposicaoDao.getIdComposicaoPorIdentificador(jTextField8.getText());
            if ((idInsumoBuscado != 0 && jRadioButton3.isSelected()) || (!jRadioButton3.isSelected() && idComposicaoBuscada != 0)) {
                ItemComposicaoDao itemComposicaoDao = new ItemComposicaoDao();
                itemComposicaoDao.setIdComposicao(idComposicaoBuscada);
                itemComposicaoDao.setIdInsumo(idInsumoBuscado);
                itemComposicaoDao.setQuantidade((int) (Format.formatarStringDouble(jTextField13.getText()) * 100));
                if (idInsumoBuscado != 0) {
                    itemComposicaoDao.setTipoItem(EnumTipoItemOrcamento.TipoItemOrcamento.INSUMO);
                    InsumoDao insumoDao = new InsumoDao();
                    insumoDao.buscar(idInsumoBuscado);
                    itemComposicaoDao.setValorUnitario(insumoDao.getValorUnitario());
                } else {
                    itemComposicaoDao.setTipoItem(EnumTipoItemOrcamento.TipoItemOrcamento.COMPOSICAO);
                    ComposicaoDao composicaoDao = new ComposicaoDao();
                    composicaoDao.buscar(idComposicaoBuscada);
                    itemComposicaoDao.setValorUnitario(composicaoDao.getValorUnitario());
                }
                if (idComposicaoBuscada != 0 && idComposicaoBuscada == idComposicao) {
                    JOptionPane.showMessageDialog(null, "Não é possível adiciar a propria composição na lista de itens.", this.getTitle(), JOptionPane.ERROR_MESSAGE);
                } else {
                    if (!jButton4.isEnabled()) {
                        listaItemComposicao.add(itemComposicaoDao);
                    } else {
                        listaItemComposicao.set(index, itemComposicaoDao);
                    }
                    limparCamposItens(true);

                    buscarTabela();
                }
            } else {
                JOptionPane.showMessageDialog(null, "Insumo/Composicação não encontrado.", this.getTitle(), JOptionPane.ERROR_MESSAGE);
            }

        } catch (Exception ex) {
            MensagemExcessao.mostrarMensagem(ex, this.getTitle());
        }
    }

    private void carregarInformacoes() {
        jButton1.setText("Editar");
        jButton1.setIcon(new Icons().getEdit());

        ComposicaoDao composicaoDao = new ComposicaoDao();
        composicaoDao.buscar(idComposicao);

        jTextField4.setText(composicaoDao.getIdentificador());
        jTextField6.setText(composicaoDao.getNome());
        jComboBox6.setSelectedItem(EnumUnidadeInsumo.ConvertEnumString(composicaoDao.getUnidadeInsumo()));
        jTextArea2.setText(composicaoDao.getObservacao());
        jTextField1.setText(Format.formatarMonetario(Double.toString(((double) composicaoDao.getValorUnitario()) / 100)));

        listaItemComposicao = ItemComposicaoDao.listarItemPorComposicaoPai(composicaoDao.getId());

        buscarTabela();
    }

    /**
     * Inicializando as configurações da tela
     *
     * @throws SQLException
     */
    private void configurarJanela() throws SQLException {
        autoCompletarIdentificadorItem = new AutoComplete(jList2, jScrollPane3, jTextField8);
        autoCompletarNomeItem = new AutoComplete(jList4, jScrollPane4, jTextField5);

        listaItemComposicao = new LinkedList<ItemComposicaoDao>();

        configureTable();

        LinkedList<String> listaUnidadesInsumos = EnumUnidadeInsumo.ListaStringUnidades();
        for (int i = 0; i < listaUnidadesInsumos.size(); i++) {
            jComboBox6.addItem(listaUnidadesInsumos.get(i).toString());
        }

        if (idComposicao != 0) {
            carregarInformacoes();
        } else {
            configurarCamposComposicao();
        }

    }

    private void selecionarItem(int idItemBuscado) {
        if (idItemBuscado == 0) {
            idItemBuscado = (jRadioButton3.isSelected()) ? InsumoDao.getIdInsumoPorIdentificador(jTextField8.getText()) : ComposicaoDao.getIdComposicaoPorIdentificador(jTextField8.getText());
            if (idItemBuscado == 0) {
                idItemBuscado = (jRadioButton3.isSelected()) ? InsumoDao.getIdInsumoPorNome(jTextField5.getText()) : ComposicaoDao.getIdComposicaoPorNome(jTextField5.getText());
            }
        }

        if (jRadioButton3.isSelected()) { // INSUMO
            InsumoDao insumoDao = new InsumoDao();
            insumoDao.buscar(idItemBuscado);
            jTextField8.setText(insumoDao.getIdentificador());
            jTextField5.setText(insumoDao.getNome());
            jTextField9.setText(EnumUnidadeInsumo.ConvertEnumString(insumoDao.getUnidadeInsumo()));

        } else {
            ComposicaoDao composicaoDao = new ComposicaoDao();
            composicaoDao.buscar(idItemBuscado);
            jTextField8.setText(composicaoDao.getIdentificador());
            jTextField5.setText(composicaoDao.getNome());
            jTextField9.setText(EnumUnidadeInsumo.ConvertEnumString(composicaoDao.getUnidadeInsumo()));

        }

    }

    public void modificarOpcaoAutocompletar(boolean opcao) {
        jTextField8.setEnabled(opcao);
        jTextField5.setEnabled(!opcao);
        jScrollPane3.setVisible(false);
        jScrollPane4.setVisible(false);
        limparCamposItens(false);
    }

    public void imprimir(int id) {
        try {
            HashMap parameters = new HashMap();

            parameters.put("idSaidaEstoque", id);
            InputStream is = this.getClass().getClassLoader().getResourceAsStream("manager/modulo/estoque/relatorio/SaidaEstoque.jasper");
            Connection connection = JanelaLogin.getConnection();
            JasperPrint relat = JasperFillManager.fillReport(is, parameters, connection);
            JasperViewer.viewReport(relat, false);
        } catch (Exception e) {
            MensagemExcessao.mostrarMensagem(e, "Saida do Estoque");
        }

    }

    public int calcularValorUnitario() {
        int valorUnitario = 0;
        for (int i = 0; i < listaItemComposicao.size(); i++) {
            ItemComposicaoDao itemComposicaoDao = listaItemComposicao.get(i);
            valorUnitario += (itemComposicaoDao.getQuantidade() * itemComposicaoDao.getValorUnitario()) / 100;
        }
        return valorUnitario;
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        buttonGroup1 = new javax.swing.ButtonGroup();
        buttonGroup2 = new javax.swing.ButtonGroup();
        jPanel3 = new javax.swing.JPanel();
        jPanel1 = new javax.swing.JPanel();
        jPanel2 = new javax.swing.JPanel();
        jButton2 = new javax.swing.JButton();
        jButton3 = new javax.swing.JButton();
        jLabel13 = new javax.swing.JLabel();
        jTextField8 = new TextFieldValidator(-1, -1, true, true, "text", jLabel13);
        jScrollPane3 = new javax.swing.JScrollPane();
        jList2 = new javax.swing.JList();
        jButton4 = new javax.swing.JButton();
        jLabel8 = new javax.swing.JLabel();
        jTextField5 = new TextFieldValidator(-1, -1, true, true, "text", jLabel8);
        jScrollPane4 = new javax.swing.JScrollPane();
        jList4 = new javax.swing.JList();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();
        jLabel11 = new javax.swing.JLabel();
        jTextField9 = new javax.swing.JTextField();
        jLabel12 = new javax.swing.JLabel();
        jTextField13 = new TextFieldValidator(10, 1, true, true, "double", jLabel11);
        jRadioButton1 = new javax.swing.JRadioButton();
        jRadioButton2 = new javax.swing.JRadioButton();
        jLabel1 = new javax.swing.JLabel();
        jRadioButton3 = new javax.swing.JRadioButton();
        jRadioButton4 = new javax.swing.JRadioButton();
        jLabel3 = new javax.swing.JLabel();
        jButton1 = new javax.swing.JButton();
        jButton6 = new javax.swing.JButton();
        jLabel7 = new javax.swing.JLabel();
        jTextField4 = new TextFieldValidator(12, -1, true, true, "text", jLabel7);
        jLabel44 = new javax.swing.JLabel();
        jScrollPane5 = new javax.swing.JScrollPane();
        jTextArea2 = new javax.swing.JTextArea();
        jLabel9 = new javax.swing.JLabel();
        jTextField6 = new TextFieldValidator(60, -1, true, true, "text", jLabel9);
        jLabel35 = new javax.swing.JLabel();
        jComboBox6 = new javax.swing.JComboBox();
        jLabel36 = new javax.swing.JLabel();
        jTextField1 = new javax.swing.JTextField();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("COMPOSIÇÃO");
        setBackground(Configurations.getBackGroundColor());
        setMinimumSize(new java.awt.Dimension(601, 450));
        addComponentListener(new java.awt.event.ComponentAdapter() {
            public void componentResized(java.awt.event.ComponentEvent evt) {
                formComponentResized(evt);
            }
        });

        jPanel3.setBackground(Configurations.getBackGroundColor());
        jPanel3.setPreferredSize(new java.awt.Dimension(700, 320));
        jPanel3.setLayout(null);

        jPanel1.setBackground(Configurations.getBackGroundColor());
        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder(""));
        jPanel1.setLayout(null);

        jPanel2.setBackground(Configurations.getBackGroundColor());
        jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder("LISTA DE INSUMOS"));
        jPanel2.setLayout(null);

        jButton2.setIcon(new javax.swing.ImageIcon(getClass().getResource("/manager/images/add.png"))); // NOI18N
        jButton2.setToolTipText("Adicionar");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });
        jPanel2.add(jButton2);
        jButton2.setBounds(520, 40, 30, 30);

        jButton3.setIcon(new javax.swing.ImageIcon(getClass().getResource("/manager/images/cancel.png"))); // NOI18N
        jButton3.setToolTipText("Cancelar");
        jButton3.setEnabled(false);
        jButton3.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton3ActionPerformed(evt);
            }
        });
        jPanel2.add(jButton3);
        jButton3.setBounds(560, 60, 30, 30);

        jLabel13.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        jLabel13.setText("Identificador");
        jPanel2.add(jLabel13);
        jLabel13.setBounds(30, 40, 90, 14);

        jTextField8.setDisabledTextColor(new java.awt.Color(51, 51, 51));
        jTextField8.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                jTextField8KeyReleased(evt);
            }
        });
        jPanel2.add(jTextField8);
        jTextField8.setBounds(10, 60, 120, 20);

        jScrollPane3.setVisible(false);

        jList2.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseReleased(java.awt.event.MouseEvent evt) {
                jList2MouseReleased(evt);
            }
        });
        jList2.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                jList2KeyReleased(evt);
            }
        });
        jScrollPane3.setViewportView(jList2);

        jPanel2.add(jScrollPane3);
        jScrollPane3.setBounds(10, 80, 120, 50);

        jButton4.setIcon(new javax.swing.ImageIcon(getClass().getResource("/manager/images/remove.png"))); // NOI18N
        jButton4.setToolTipText("Remover");
        jButton4.setEnabled(false);
        jButton4.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton4ActionPerformed(evt);
            }
        });
        jPanel2.add(jButton4);
        jButton4.setBounds(560, 20, 30, 30);

        jLabel8.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        jLabel8.setText("Nome do Insumo");
        jPanel2.add(jLabel8);
        jLabel8.setBounds(150, 40, 110, 14);

        jTextField5.setDisabledTextColor(new java.awt.Color(51, 51, 51));
        jTextField5.setEnabled(false);
        jTextField5.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                jTextField5KeyReleased(evt);
            }
        });
        jPanel2.add(jTextField5);
        jTextField5.setBounds(135, 60, 250, 20);

        jScrollPane4.setVisible(false);

        jList4.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseReleased(java.awt.event.MouseEvent evt) {
                jList4MouseReleased(evt);
            }
        });
        jList4.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                jList4KeyReleased(evt);
            }
        });
        jScrollPane4.setViewportView(jList4);

        jPanel2.add(jScrollPane4);
        jScrollPane4.setBounds(135, 80, 250, 50);

        jScrollPane1.setViewportView(jTable1);

        jPanel2.add(jScrollPane1);
        jScrollPane1.setBounds(10, 90, 580, 180);

        jLabel11.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        jLabel11.setText("Quantidade");
        jPanel2.add(jLabel11);
        jLabel11.setBounds(445, 40, 70, 14);

        jTextField9.setDisabledTextColor(new java.awt.Color(51, 51, 51));
        jTextField9.setEnabled(false);
        jPanel2.add(jTextField9);
        jTextField9.setBounds(390, 60, 50, 20);

        jLabel12.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        jLabel12.setText("Unidade");
        jPanel2.add(jLabel12);
        jLabel12.setBounds(390, 40, 50, 14);

        jTextField13.setDisabledTextColor(new java.awt.Color(51, 51, 51));
        jPanel2.add(jTextField13);
        jTextField13.setBounds(445, 60, 70, 20);

        jRadioButton1.setBackground(Configurations.getBackGroundColor());
        buttonGroup1.add(jRadioButton1);

        buttonGroup1.add(jRadioButton1);
        jPanel2.add(jRadioButton1);
        jRadioButton1.setBounds(130, 35, 21, 21);

        jRadioButton2.setBackground(Configurations.getBackGroundColor());
        buttonGroup1.add(jRadioButton2);
        jRadioButton2.setSelected(true);
        jRadioButton2.addItemListener(new java.awt.event.ItemListener() {
            public void itemStateChanged(java.awt.event.ItemEvent evt) {
                jRadioButton2ItemStateChanged(evt);
            }
        });
        jPanel2.add(jRadioButton2);
        jRadioButton2.setBounds(10, 35, 21, 21);

        jLabel1.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        jLabel1.setText("Insumo");
        jPanel2.add(jLabel1);
        jLabel1.setBounds(50, 20, 50, 14);

        jRadioButton3.setBackground(Configurations.getBackGroundColor());
        buttonGroup2.add(jRadioButton3);
        jRadioButton3.setSelected(true);
        jRadioButton3.addItemListener(new java.awt.event.ItemListener() {
            public void itemStateChanged(java.awt.event.ItemEvent evt) {
                jRadioButton3ItemStateChanged(evt);
            }
        });
        jPanel2.add(jRadioButton3);
        jRadioButton3.setBounds(30, 20, 20, 15);

        jRadioButton4.setBackground(Configurations.getBackGroundColor());
        buttonGroup2.add(jRadioButton4);
        jPanel2.add(jRadioButton4);
        jRadioButton4.setBounds(100, 20, 20, 15);

        jLabel3.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        jLabel3.setText("Composição");
        jPanel2.add(jLabel3);
        jLabel3.setBounds(120, 20, 80, 14);

        jPanel1.add(jPanel2);
        jPanel2.setBounds(15, 140, 600, 280);

        jButton1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/manager/images/add.png"))); // NOI18N
        jButton1.setText("Cadastrar");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });
        jPanel1.add(jButton1);
        jButton1.setBounds(10, 420, 100, 23);

        jButton6.setIcon(new javax.swing.ImageIcon(getClass().getResource("/manager/images/cancel.png"))); // NOI18N
        jButton6.setText("Cancelar");
        jButton6.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton6ActionPerformed(evt);
            }
        });
        jPanel1.add(jButton6);
        jButton6.setBounds(120, 420, 100, 23);

        jLabel7.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        jLabel7.setText("Identificador");
        jPanel1.add(jLabel7);
        jLabel7.setBounds(20, 10, 80, 14);

        jTextField4.setDisabledTextColor(new java.awt.Color(51, 51, 51));
        jPanel1.add(jTextField4);
        jTextField4.setBounds(20, 30, 130, 20);

        jLabel44.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        jLabel44.setText("Observação");
        jPanel1.add(jLabel44);
        jLabel44.setBounds(20, 60, 80, 14);

        jTextArea2.setColumns(20);
        jTextArea2.setFont(new java.awt.Font("Monospaced", 1, 10)); // NOI18N
        jTextArea2.setLineWrap(true);
        jTextArea2.setRows(2);
        jTextArea2.setWrapStyleWord(true);
        jScrollPane5.setViewportView(jTextArea2);
        jTextArea2.setDocument(new FixedLengthDocument(150));

        jPanel1.add(jScrollPane5);
        jScrollPane5.setBounds(20, 80, 590, 50);

        jLabel9.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        jLabel9.setText("Nome");
        jPanel1.add(jLabel9);
        jLabel9.setBounds(155, 10, 80, 14);

        jTextField6.setDisabledTextColor(new java.awt.Color(51, 51, 51));
        jPanel1.add(jTextField6);
        jTextField6.setBounds(155, 30, 315, 20);

        jLabel35.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        jLabel35.setText("Unidade");
        jPanel1.add(jLabel35);
        jLabel35.setBounds(475, 10, 50, 14);

        jPanel1.add(jComboBox6);
        jComboBox6.setBounds(475, 30, 50, 20);

        jLabel36.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        jLabel36.setText("Valor Calculado");
        jPanel1.add(jLabel36);
        jLabel36.setBounds(530, 10, 90, 14);

        jTextField1.setDisabledTextColor(new java.awt.Color(51, 51, 51));
        jTextField1.setEnabled(false);
        jPanel1.add(jTextField1);
        jTextField1.setBounds(530, 30, 80, 20);

        jPanel3.add(jPanel1);
        jPanel1.setBounds(0, 0, 620, 450);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jPanel3, javax.swing.GroupLayout.DEFAULT_SIZE, 621, Short.MAX_VALUE)
                .addGap(0, 0, 0))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel3, javax.swing.GroupLayout.DEFAULT_SIZE, 450, Short.MAX_VALUE)
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void formComponentResized(java.awt.event.ComponentEvent evt) {//GEN-FIRST:event_formComponentResized
        WindowsFunctions.resizePanel(jPanel3, jPanel1);
    }//GEN-LAST:event_formComponentResized

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        LinkedList<String> fieldValidadeList = validarCamposEntradaEstoque();
        if (fieldValidadeList.size() == 0) {
            if (idComposicao == 0) {
                adicionarComposicao();
            } else {
                editarComposicao();
            }
        } else {
            JOptionPane.showMessageDialog(null, ValidationFunctions.getValidationMessage(fieldValidadeList), this.getTitle(), JOptionPane.ERROR_MESSAGE);
        }
    }//GEN-LAST:event_jButton1ActionPerformed

    private void jButton6ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton6ActionPerformed
        this.dispose();
    }//GEN-LAST:event_jButton6ActionPerformed

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
        LinkedList<String> fieldValidadeList = validarCamposInsumos();
        if (fieldValidadeList.size() == 0) {
            adicionarItemComposicao();
        } else {
            JOptionPane.showMessageDialog(null, ValidationFunctions.getValidationMessage(fieldValidadeList), this.getTitle(), JOptionPane.ERROR_MESSAGE);
        }
}//GEN-LAST:event_jButton2ActionPerformed

    private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed
        limparCamposItens(true);
}//GEN-LAST:event_jButton3ActionPerformed

    private void jTextField8KeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jTextField8KeyReleased
        try {
            if (evt.getKeyCode() == KeyEvent.VK_ENTER) {
                selecionarItem(0);
            } else if (evt.getKeyCode() == KeyEvent.VK_DOWN) {
                if (autoCompletarIdentificadorItem.getjScrollPane().isVisible()) {
                    autoCompletarIdentificadorItem.getjList().setSelectedIndex(0);
                    autoCompletarIdentificadorItem.getjList().requestFocus();
                }
            } else {
                if (!autoCompletarIdentificadorItem.getSearchWord().equals(jTextField8.getText())) {
                    autoCompletarIdentificadorItem.setSearchWord(jTextField8.getText());
                    String opcao = (jRadioButton3.isSelected() ? "Identificador Insumo" : "Identificador Composicao");
                    autoCompletarIdentificadorItem.update(new ItemOrcamentoDao().buscar(opcao, jTextField8.getText(), true));
                }
            }
        } catch (Exception e) {
            MensagemExcessao.mostrarMensagem(e, this.getTitle());
        }
    }//GEN-LAST:event_jTextField8KeyReleased

    private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton4ActionPerformed
        listaItemComposicao.remove(index);
        limparCamposItens(true);
        buscarTabela();
    }//GEN-LAST:event_jButton4ActionPerformed

    private void jList2KeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jList2KeyReleased
        if (evt.getKeyCode() == KeyEvent.VK_ENTER) {
            autoCompletarIdentificadorItem.setSearchWord(autoCompletarIdentificadorItem.getjList().getSelectedValue().toString());
            autoCompletarIdentificadorItem.getjScrollPane().setVisible(false);
            selecionarItem(0);
        }
    }//GEN-LAST:event_jList2KeyReleased

    private void jList2MouseReleased(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jList2MouseReleased
        autoCompletarIdentificadorItem.setSearchWord(autoCompletarIdentificadorItem.getjList().getSelectedValue().toString());
        autoCompletarIdentificadorItem.getjScrollPane().setVisible(false);
        selecionarItem(0);
    }//GEN-LAST:event_jList2MouseReleased

    private void jList4MouseReleased(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jList4MouseReleased
        autoCompletarNomeItem.setSearchWord(autoCompletarNomeItem.getjList().getSelectedValue().toString());
        autoCompletarNomeItem.getjScrollPane().setVisible(false);
        selecionarItem(0);
    }//GEN-LAST:event_jList4MouseReleased

    private void jList4KeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jList4KeyReleased
        if (evt.getKeyCode() == KeyEvent.VK_ENTER) {
            autoCompletarNomeItem.setSearchWord(autoCompletarNomeItem.getjList().getSelectedValue().toString());
            autoCompletarNomeItem.getjScrollPane().setVisible(false);
            selecionarItem(0);
        }
    }//GEN-LAST:event_jList4KeyReleased

    private void jRadioButton2ItemStateChanged(java.awt.event.ItemEvent evt) {//GEN-FIRST:event_jRadioButton2ItemStateChanged
        modificarOpcaoAutocompletar(jRadioButton2.isSelected());
    }//GEN-LAST:event_jRadioButton2ItemStateChanged

    private void jTextField5KeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jTextField5KeyReleased
        try {
            if (evt.getKeyCode() == KeyEvent.VK_ENTER) {
                selecionarItem(0);
            } else if (evt.getKeyCode() == KeyEvent.VK_DOWN) {
                if (autoCompletarNomeItem.getjScrollPane().isVisible()) {
                    autoCompletarNomeItem.getjList().setSelectedIndex(0);
                    autoCompletarNomeItem.getjList().requestFocus();
                }
            } else {
                if (!autoCompletarNomeItem.getSearchWord().equals(jTextField5.getText())) {
                    autoCompletarNomeItem.setSearchWord(jTextField5.getText());
                    String opcao = (jRadioButton3.isSelected() ? "Nome Insumo" : "Nome Composicao");
                    autoCompletarNomeItem.update(new ItemOrcamentoDao().buscar(opcao, jTextField5.getText(), true));
                }
            }
        } catch (Exception e) {
            MensagemExcessao.mostrarMensagem(e, this.getTitle());
        }
    }//GEN-LAST:event_jTextField5KeyReleased

    private void jRadioButton3ItemStateChanged(java.awt.event.ItemEvent evt) {//GEN-FIRST:event_jRadioButton3ItemStateChanged
        limparCamposItens(false);
    }//GEN-LAST:event_jRadioButton3ItemStateChanged

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.ButtonGroup buttonGroup1;
    private javax.swing.ButtonGroup buttonGroup2;
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JButton jButton3;
    private javax.swing.JButton jButton4;
    private javax.swing.JButton jButton6;
    private javax.swing.JComboBox jComboBox6;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel11;
    private javax.swing.JLabel jLabel12;
    private javax.swing.JLabel jLabel13;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel35;
    private javax.swing.JLabel jLabel36;
    private javax.swing.JLabel jLabel44;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JLabel jLabel8;
    private javax.swing.JLabel jLabel9;
    private javax.swing.JList jList2;
    private javax.swing.JList jList4;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JRadioButton jRadioButton1;
    private javax.swing.JRadioButton jRadioButton2;
    private javax.swing.JRadioButton jRadioButton3;
    private javax.swing.JRadioButton jRadioButton4;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane3;
    private javax.swing.JScrollPane jScrollPane4;
    private javax.swing.JScrollPane jScrollPane5;
    private javax.swing.JTable jTable1;
    private javax.swing.JTextArea jTextArea2;
    private javax.swing.JTextField jTextField1;
    private javax.swing.JTextField jTextField13;
    private javax.swing.JTextField jTextField4;
    private javax.swing.JTextField jTextField5;
    private javax.swing.JTextField jTextField6;
    private javax.swing.JTextField jTextField8;
    private javax.swing.JTextField jTextField9;
    // End of variables declaration//GEN-END:variables
}
